package com.tengju.user.infrastructure.persistence.es;

import com.tengju.data.domain.model.user.UserLevelEnum;
import com.tengju.user.application.user.dto.UserSearchForm;
import com.tengju.user.domain.model.doc.UserDocument;
import com.tengju.user.domain.model.sign.StarSignStatus;
import com.tengju.user.domain.shared.IdObject;
import org.elasticsearch.index.query.*;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class UserSearchDocConvert {

    public static QueryBuilder formToQuery(UserSearchForm form) {
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        if (form.getTjUserId() != null) {
            queryBuilder
                    .must(QueryBuilders.termQuery(UserDocument.TJ_USER_ID, form.getTjUserId().getValue()));
        }
        if (form.getAbmUserId() != null) {
            queryBuilder
                    .must(QueryBuilders.termQuery(UserDocument.ABM_USER_ID, form.getAbmUserId().getValue()));
        }
        if (form.getIdCode() != null) {
            queryBuilder
                    .must(QueryBuilders.termQuery(UserDocument.ID_CODE, form.getIdCode().getValue()));
        }
        if (!StringUtils.isEmpty(form.getMobile())) {
            queryBuilder
                    .must(QueryBuilders.matchQuery(UserDocument.MOBILE, form.getMobile()));
        }
        if (!StringUtils.isEmpty(form.getNickname())) {
            queryBuilder
                    .must(QueryBuilders.termQuery(UserDocument.NICKNAME, form.getNickname()));
        }
        if (form.getPidCode() != null) {
            queryBuilder
                    .must(QueryBuilders.termQuery(UserDocument.PARENT_ID_CODE, form.getPidCode().getValue()));
        }
        if (form.getStarLevel() != null) {
            queryBuilder
                    .must(QueryBuilders.termQuery(UserDocument.STAR_LEVEL, form.getStarLevel().getCode()));
        }
        if (!CollectionUtils.isEmpty(form.getSignStatusList()) && form.getSignStatusList().size() > 0) {
            List<Integer> signStatusList = form.getSignStatusList().stream()
                    .map(StarSignStatus::getVal).collect(Collectors.toList());
            queryBuilder
                    .must(QueryBuilders.termsQuery(UserDocument.STAR_SIGN_STATUS, signStatusList));
        }
        if (form.getTargetStarLevel() != null) {
            queryBuilder
                    .must(QueryBuilders.termQuery(UserDocument.TARGET_STAR_LEVEL, form.getTargetStarLevel().getCode()));
        }
        if (form.getSignTargetStarLevel() != null) {
            queryBuilder
                    .must(QueryBuilders.termQuery(UserDocument.SIGN_TARGET_STAR_LEVEL, form.getSignTargetStarLevel().getCode()));
        }
        if (!CollectionUtils.isEmpty(form.getClubIds()) && form.getClubIds().size() > 0) {
            List<Long> clubIdLongList = form.getClubIds().stream()
                    .map(IdObject::getValue).collect(Collectors.toList());
            queryBuilder
                    .must(QueryBuilders.termsQuery(UserDocument.CLUB_ID, clubIdLongList));
        }
        if (!CollectionUtils.isEmpty(form.getIdCodes()) && form.getIdCodes().size() > 0) {
            List<Long> idCodeValList = form.getIdCodes().stream()
                    .map(IdObject::getValue).collect(Collectors.toList());
            queryBuilder
                    .must(QueryBuilders.termsQuery(UserDocument.ID_CODE, idCodeValList));
        }

        if (!CollectionUtils.isEmpty(form.getOwnerGenSecIdCodes()) && form.getOwnerGenSecIdCodes().size() > 0) {
            queryBuilder
                    .must(QueryBuilders.termsQuery(UserDocument.OWNER_GEN_SEC_ID_CODE, form.getOwnerGenSecIdCodes()));
        }

        if (!StringUtils.isEmpty(form.getKeyWords()) && form.getLeaderId() != null) {

            queryBuilder.must(
                    QueryBuilders.boolQuery()
                            .should(
                                    QueryBuilders.boolQuery()
                                            .must(QueryBuilders.termQuery(UserDocument.MOBILE, form.getKeyWords()))
                            )
                            .should(
                                    QueryBuilders.boolQuery()
                                            .must(QueryBuilders.matchQuery(UserDocument.NICKNAME, form.getKeyWords()))
                            )
                            .should(
                                    QueryBuilders.boolQuery()
                                            .must(QueryBuilders.termQuery(UserDocument.DOMINATION_NOTE_LEADER, form.getLeaderId()))
                                            .must(QueryBuilders.matchQuery(UserDocument.DOMINATION_NOTE_REMARK, form.getKeyWords()).operator(Operator.AND))
                            )

            );

        }

        if (!StringUtils.isEmpty(form.getServiceProviderIdAndNicknameAndMobile())) {
            String regular = "^[0-9]*$";
            if (Pattern.compile(regular).matcher(form.getServiceProviderIdAndNicknameAndMobile()).matches()){
                queryBuilder.must(
                        QueryBuilders.boolQuery()
                                .should(
                                        QueryBuilders.boolQuery()
                                                .must(QueryBuilders.termQuery(UserDocument.ID_CODE, form.getServiceProviderIdAndNicknameAndMobile()))
                                )
                                .should(
                                        QueryBuilders.boolQuery()
                                                .must(QueryBuilders.matchQuery(UserDocument.NICKNAME, form.getServiceProviderIdAndNicknameAndMobile()))
                                )
                                .should(
                                        QueryBuilders.boolQuery()
                                                .must(QueryBuilders.termQuery(UserDocument.MOBILE, form.getServiceProviderIdAndNicknameAndMobile()))
                                )

                );
            }else {
                queryBuilder.must(
                        QueryBuilders.boolQuery()
                                .should(
                                        QueryBuilders.boolQuery()
                                                .must(QueryBuilders.matchQuery(UserDocument.NICKNAME, form.getServiceProviderIdAndNicknameAndMobile()))
                                )
                                .should(
                                        QueryBuilders.boolQuery()
                                                .must(QueryBuilders.termQuery(UserDocument.MOBILE, form.getServiceProviderIdAndNicknameAndMobile()))
                                )
                );
            }

        }

        if (!StringUtils.isEmpty(form.getSentimentContext())) {
            queryBuilder.must(QueryBuilders.matchQuery(UserDocument.SENTIMENT_CONTEXT, form.getSentimentContext()));
        }

        if (form.getOwnerEcIdCode() != null && form.getOwnerEcIdCode() > 0) {
            queryBuilder.must(QueryBuilders.termQuery(UserDocument.OWNER_EC_ID_CODE, form.getOwnerEcIdCode()));
        }

        if (form.getOwnerGenSecIdCode() != null && form.getOwnerGenSecIdCode() > 0) {
            queryBuilder.must(QueryBuilders.termQuery(UserDocument.OWNER_GEN_SEC_ID_CODE, form.getOwnerGenSecIdCode()));
        }

        if (form.getOwnerCityIdCode() != null && form.getOwnerCityIdCode() > 0) {
            queryBuilder.must(QueryBuilders.termQuery(UserDocument.OWNER_CITY_ID_CODE, form.getOwnerCityIdCode()));
        }

//        if (form.getMonthNewStartTime() != null || form.getMonthNewEndTime() != null) {
//            RangeQueryBuilder starAddDate = QueryBuilders
//                    .rangeQuery(UserDocument.STAR_ADD_DATE)
//                    .includeLower(true)
//                    .includeUpper(true);
//            RangeQueryBuilder blackAddDate = QueryBuilders
//                    .rangeQuery(UserDocument.BLACK_ADD_DATE)
//                    .includeLower(true)
//                    .includeUpper(true);
//            if (form.getMonthNewStartTime() != null) {
//                starAddDate.gte(form.getMonthNewStartTime());
//                blackAddDate.gte(form.getMonthNewStartTime());
//            }
//            if (form.getMonthNewEndTime() != null) {
//                starAddDate.lte(form.getMonthNewEndTime());
//                blackAddDate.lte(form.getMonthNewEndTime());
//            }
//            queryBuilder.must(QueryBuilders.boolQuery()
//                    .should(QueryBuilders.boolQuery().must(QueryBuilders.existsQuery(UserDocument.STAR_ADD_DATE))
//                            .must(starAddDate))
//                    .should(QueryBuilders.boolQuery().must(QueryBuilders.existsQuery(UserDocument.BLACK_ADD_DATE))
//                            .must(blackAddDate))
//
//            );
//        }


        if (form.getMonthNewStartTime() != null || form.getMonthNewEndTime() != null) {
            RangeQueryBuilder starAddDate = QueryBuilders
                    .rangeQuery(UserDocument.LAST_DEMOTION_TIME)
                    .includeLower(true)
                    .includeUpper(true);
            if (form.getMonthNewStartTime() != null) {
                starAddDate.gte(form.getMonthNewStartTime());
            }
            if (form.getMonthNewEndTime() != null) {
                starAddDate.lte(form.getMonthNewEndTime());
            }
            queryBuilder.must(
                QueryBuilders.boolQuery()
                    .must(QueryBuilders.boolQuery().must(QueryBuilders.existsQuery(UserDocument.STAR_ADD_DATE))
                            .must(starAddDate))
                    .must(QueryBuilders.termQuery(UserDocument.LAST_DEMOTION_OPERATING, 1))

            );
        }

        // 默认只查询黑卡数据
        queryBuilder.must(QueryBuilders.termQuery(UserDocument.BRAND_PROVIDER_LEVEL, UserLevelEnum.BLACK.getCode()));

        return queryBuilder;
    }
}
